//
//  OADShareItViewController.m
//  OASDK_Works
//
//  Created by ChenJie on 5/9/20.
//  Copyright © 2020 Mist. All rights reserved.
//

#import "OADShareItViewController.h"
#import "SGQRCode.h"

@interface OADShareItViewController ()

@property (nonatomic, strong) UIBarButtonItem *shareButtonItem;

@end

@implementation OADShareItViewController

#pragma mark - ViewController lifecycle

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = NSStringFromClass(self.class);
    
    //
    self.navigationItem.rightBarButtonItem = self.shareButtonItem;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    //
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - Public methods



#pragma mark - Private methods

- (void)shareIt {
//    NSString *title = @"吴说家";
//    NSString *content = @"合同附件";
//    UIImage *thumbnail = [UIImage imageNamed:@"weiXinShare.jpg"];
//    NSString *urlString = @"http://appdemo.outsourceax.net:35086//OneClickSharing/Information?Id=227815&timestamp=1589033879&type=6";
    
    NSString *urlString = @"http://download.wheelpool.cn/software/downloadAPP.html";
    UIImage *image = [SGQRCodeObtain generateQRCodeWithData:urlString size:260 logoImage:[UIImage imageNamed:@"WechatIMG80"] ratio:0.2];
    UIImage *thumbnail = [self compressImage:image toByte:32765];
    
//    [self shareImage:thumbnail];
    
    [self shareWithTitle:@"分享"
                 content:nil
                   image:thumbnail
               urlString:nil];
}

- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

- (void)shareWithTitle:(NSString *)title
               content:(NSString *)content
                 image:(UIImage *)image
             urlString:(NSString *)urlString {
    
    NSMutableArray *items = [NSMutableArray array];
    
    //
    NSString *shareTitle = title;
    if (content) {
        shareTitle = [NSString stringWithFormat:@"%@ - %@", shareTitle, content];
    }
    if (shareTitle) {
        [items addObject:shareTitle];
    }
    
    //
    image = image ?: [UIImage imageNamed:@"weiXinShare.jpg"];
    [items addObject:image];
    
    //
    NSURL *shareURL = [NSURL URLWithString:urlString];
    if (shareURL) {
        [items addObject:shareURL];
    }
    
    UIActivityViewController *vc =
    [[UIActivityViewController alloc] initWithActivityItems:items
                                      applicationActivities:nil];
    
    UIActivityViewControllerCompletionWithItemsHandler myBlock =
    ^(UIActivityType activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
        if (completed) {
            NSLog(@"分享成功");
        } else {
            NSLog(@"分享失败");
        }
        [vc dismissViewControllerAnimated:YES completion:nil];
    };
    vc.completionWithItemsHandler = myBlock;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - Event response methods

- (void)buttonClicked:(UIButton *)button {
    NSLog(@"button clicked...");
}

- (void)shareIt:(UIBarButtonItem *)buttonItem {
    [self shareIt];
}

#pragma mark - Deletate methods



#pragma mark - Setter



#pragma mark - Getter

- (UIBarButtonItem *)shareButtonItem {
    if (!_shareButtonItem) {
        UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"Share"
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:self
                                                                      action:@selector(shareIt:)];
        _shareButtonItem = buttonItem;
    }
    return _shareButtonItem;
}

#pragma mark - Memory management

- (void)dealloc {
}

@end
